package com.knife.blog.logic.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.knife.blog.domain.BlogInfo;
import com.knife.blog.domain.BlogUser;
import com.knife.blog.logic.BlogUserService;
import com.knife.blog.mail.SendMail;
import com.knife.blog.service.Config;
import com.knife.util.CommUtil;
import com.knife.util.MD5;
import com.knife.web.ActionContext;
import com.knife.web.Globals;
import com.knife.web.tools.ActiveUser;
import com.knife.web.tools.DbPageList;
import com.knife.web.tools.IActiveUser;
import com.knife.web.tools.IPageList;
import com.knife.blog.domain.BlogNewsDoc;

public class BlogUserServiceImpl extends DAOSupportService implements
        BlogUserService {

    private String userSite = "http://www.knifecms.com/";
    private String checkLoginApp = "bloguser.do?parameter=remotUserLogin";
    private static BlogUserServiceImpl singleton = new BlogUserServiceImpl();
    private static BlogCoreServiceImpl blogdocservice = new BlogCoreServiceImpl();

    public static BlogUserServiceImpl getInstance() {
        return singleton;
    }

    public boolean changePassword(String username, String oldPassword,
            String newPassword) {
        // TODO Auto-generated method stub
        BlogUser user = (BlogUser) this.dao.getBy(BlogUser.class, "username",
                username);
        // BlogUser u=getBlogUser(username);
        if (MD5.encode(CommUtil.null2String(oldPassword)).equals(
                user.getPassword().trim())) {
        	user.setUsername(username);
            user.setPassword(MD5.encode(CommUtil.null2String(newPassword)));
            this.dao.update(user);
            return true;
        } else {
            return false;
        }
    }

    public boolean changePassword(BlogUser user, String newPassword) {
        if ("".equals(newPassword)) {
            return false;
        }
        user.setPassword(MD5.encode(CommUtil.null2String(newPassword)));
        boolean ret = this.dao.update(user);
        return ret;
    }

    public boolean delBlogInfo(String cid) {
        boolean ret = false;
        BlogUser bloguser = getBlogUser("cid", cid);
        if (bloguser == null) {
            return true;
        }
        String username = bloguser.getUsername();
        //删除用户博客中的文章
        blogdocservice.delUserBlogNewsDoc(username);
        //删除用户博客中的分类
        blogdocservice.delUserBlogNewsDir(username);
        ret = this.dao.del(bloguser);// 删除用户信息
        BlogInfo bloginfo = getUserBlog("username", username);
        ret = this.dao.del(bloginfo);// 删除博客信息
        // 用户的文件夹也应该删除
        ret = this.removeBlog(bloginfo);
        return ret;
    }

    public boolean delUserInfo(String name) {
        boolean ret = false;
        BlogUser bloguser = getBlogUser("username", name);
        if (bloguser == null) {
            return true;
        }
        ret = this.dao.del(bloguser);// 删除用户信息
        return ret;
    }

    public BlogInfo getBlogInfo(String cid) {
        return (BlogInfo) this.dao.get(BlogInfo.class, cid);
    }

    public BlogInfo getUserBlog(String username) {
        return (BlogInfo) this.dao.getBy(BlogInfo.class, "username", username);
    }

    public BlogInfo getUserBlog(String fieldName, String value) {
        return (BlogInfo) this.dao.getBy(BlogInfo.class, fieldName, value);
    }

    public BlogUser getBlogUser(String username) {
        return (BlogUser) this.dao.getBy(BlogUser.class, "username", username);
    }

    public BlogUser getBlogUser(String fieldName, String value) {
        return (BlogUser) this.dao.getBy(BlogUser.class, fieldName, value);
    }

    public ActiveUserImpl login(String username, String password, String ip) {
        ActiveUserImpl user = null;
        BlogUser u = (BlogUser) this.dao.getBy(BlogUser.class, "username",username);
        if (u != null
                && MD5.encode(CommUtil.null2String(password)).equals(
                u.getPassword().trim())) {
        	System.out.println("从对象中获取的用户名是："+u.getUsername()+",密码是："+u.getPassword()+",传入的用户名是:"+username);
            user = new ActiveUserImpl();
            user.setUserName(username);
            user.setIp(ip);
            user.setCurPosition("当前位置");
            user.setPassword(u.getPassword().trim());
            user.setLoginTime(new Date());
            user.setStatus(u.getStatus());
            u.setUsername(username);
            u.setLastloginip(ip);
            u.setLogintimes(new Integer(u.getLogintimes() == null ? 1 : u.getLogintimes().intValue() + 1));
            u.setLastlogintime(new Date());
            this.dao.update(u);
        }
        // System.out.println("bloguser:"+user);
        return user;
    }

    public IActiveUser remotLogin(String username, String password, String ip) {
        SAXReader reader = new SAXReader();
        ActiveUser user = null;
        try {
            String url = userSite + checkLoginApp + "&user="
                    + URLEncoder.encode(username, "utf-8") + "&password="
                    + password + "&ip=" + ip;
            Document doc = reader.read(url);
            Element root = doc.getRootElement();
            List list = root.elements();
            java.util.Map map = new java.util.HashMap();
            for (int i = 0; i < list.size(); i++) {
                Element e = (Element) list.get(i);
                String fieldName = e.attributeValue("name");
                map.put(fieldName, e.getTextTrim());
            }
            user = new ActiveUser();
            CommUtil.Map2Obj(map, user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    public IPageList queryUserInfo(String orderBy, int currentPage, int pageSize) {
        String scope = "1=1 order by " + orderBy;
        DbPageList pList = new DbPageList(BlogUser.class, scope);
        pList.doList(currentPage, pageSize);
        return pList;
    }

    public IPageList queryUserInfo(String orderBy, int currentPage,
            int pageSize, int status) {
        String scope = "status=" + status + " and username!='admin' order by " + orderBy;
        DbPageList pList = new DbPageList(BlogUser.class, scope);
        pList.doList(currentPage, pageSize);
        return pList;
    }

    public boolean updateUserInfo(BlogUser blogUser) {
        boolean ret = false;
        ret = this.dao.update(blogUser);
        if (ret && blogUser.getStatus() == 1) {
            BlogInfo blogInfo = getUserBlog(blogUser.getUsername());
            //com.knife.blog.logic.HTMLGenerater.saveLeftPersonInfoToHTML(blogInfo);// 更新个人信息模块
            com.knife.blog.logic.HTMLGenerater.saveToHTML(blogInfo);
        }
        return ret;
    }

    public IPageList queryBlogInfo(String types, String orderBy,
            int currentPage, int pageSize) {
        String scope = "types=? order by " + orderBy;
        java.util.Collection<Object> paras = new java.util.ArrayList<Object>();
        paras.add(types);
        DbPageList pList = new DbPageList(BlogInfo.class, scope, paras);
        pList.doList(currentPage, pageSize);
        return pList;
    }

    public IPageList queryEliteBlogInfo(String orderBy, int currentPage,
            int pageSize) {
        String scope = "elite>0 order by " + orderBy;
        java.util.Collection<Object> paras = new java.util.ArrayList<Object>();
        DbPageList pList = new DbPageList(BlogInfo.class, scope, paras);
        pList.doList(currentPage, pageSize);
        return pList;
    }

    public boolean register(BlogUser blogUser) {
        return false;
    }

    public boolean check(String cid) {
        boolean ret = false;
        BlogUser bloguser = getBlogUser("cid", cid);
        if (bloguser == null) {
            return false;
        }
        BlogInfo bloginfo = getUserBlog("username", bloguser.getUsername());
        if (bloginfo == null) {
            return false;
        }
        bloginfo.setStatus(1);
        ret = this.dao.update(bloginfo);
        bloguser.setStatus(1);
        ret = this.dao.update(bloguser);
        com.knife.blog.logic.HTMLGenerater.generateBlog(bloginfo);
        return ret;
    }

    public boolean generateBlog(String cid) {
        boolean ret = false;
        BlogUser bloguser = getBlogUser("cid", cid);
        if (bloguser == null) {
            return false;
        }
        BlogInfo bloginfo = getUserBlog("username", bloguser.getUsername());
        if (bloginfo == null) {
            return false;
        }
        try{
            com.knife.blog.logic.HTMLGenerater.generateBlog(bloginfo);
            ret=true;
        }catch(Exception e){return false;}
        return ret;
    }

    public boolean unCheck(String cid) {
        boolean ret = false;
        BlogUser bloguser = getBlogUser("cid", cid);
        if (bloguser == null) {
            return false;
        }
        BlogInfo bloginfo = getUserBlog("username", bloguser.getUsername());
        if (bloginfo == null) {
            return false;
        }
        bloginfo.setStatus(0);
        ret = this.dao.update(bloginfo);
        bloguser.setStatus(0);
        ret = this.dao.update(bloguser);
        //com.knife.blog.logic.HTMLGenerater.checkUser(bloginfo);
        return ret;
    }

    public boolean updaeElite(BlogInfo blog) {
        IPageList Ilist = queryEliteBlogInfo("inputtime desc", 1, 1);
        List list = Ilist.getResult();
        boolean ret = false;
        if (blog == null) {
            return false;
        }
        blog.setElite(2);
        ret = this.dao.update(blog);
        if (ret == false) {
            return ret;
        }
        // 将其它博客的Elite设为1，因为只需要一个
        if (list != null) {
            BlogInfo blotemp = (BlogInfo) list.get(0);
            blotemp.setElite(0);
            this.dao.update(blotemp);
        }
        return ret;
    }

    public boolean register(BlogInfo blogInfo) {
        boolean ret = false;
        if (getUserBlog(blogInfo.getUsername()) != null) {
            return false;
        }
        if (blogInfo.getDomain().equals("images")
                || blogInfo.getDomain().equals("style")) {
            return false;
        }

        blogInfo.setInputtime(new Date());
        blogInfo.setReadtimes(new Integer(0));
        java.util.Collection<Object> paras = new java.util.ArrayList<Object>();
        paras.add(blogInfo.getUsername());
        paras.add(blogInfo.getDomain());
        Number num = (Number) this.dao.uniqueResult(
                "select count(*) from bloginfo where username!=? and domain=?",
                paras);
        if (num.intValue() > 0) {
            System.out.println(new Date() + ":域名重复");
            return false;
        }
        paras.clear();
        paras.add(blogInfo.getUsername());
        paras.add(blogInfo.getEmail());
        num = (Number) this.dao.uniqueResult(
                "select count(*) from bloginfo where username!=? and email=?",
                paras);
        if (num.intValue() > 0) {
            System.out.println(new Date() + ":邮箱重复");
            return false;
        }

        ret = this.dao.save(blogInfo);
        if (ret) {
            try {
                if (blogInfo.getStatus() == 1) {
                    BlogUser bloguser = getBlogUser(blogInfo.getUsername());
                    bloguser.setStatus(1);
                    this.dao.update(bloguser);
                    com.knife.blog.logic.HTMLGenerater.generateBlog(blogInfo);// 如果是审核过的，则生成用户博客首页，相册首页，留言首页
                } else {
                    System.out.println(new Date() + ":此用户还未通过审核");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    public boolean settingBlogInfo(BlogInfo blogInfo) { // 更改博客信息
        boolean ret = false;
        java.util.Collection<Object> paras = new java.util.ArrayList<Object>();
        paras.add(blogInfo.getUsername());
        paras.add(blogInfo.getDomain());
        Number num = (Number) this.dao.uniqueResult(
                "select count(*) from bloginfo where username!=? and domain=?",
                paras);
        if (num.intValue() > 0) {
            System.out.println(new Date() + ":域名重复");
            return false;
        }
        paras.clear();
        paras.add(blogInfo.getUsername());
        paras.add(blogInfo.getEmail());
        num = (Number) this.dao.uniqueResult(
                "select count(*) from bloginfo where username!=? and email=?",
                paras);
        if (num.intValue() > 0) {
            System.out.println(new Date() + ":邮箱重复");
            return false;
        }

        ret = this.dao.update(blogInfo);
        if (ret && blogInfo.getStatus() == 1) {
            com.knife.blog.logic.HTMLGenerater.saveLeftPersonInfoToHTML(blogInfo);// 更新个人信息模块
        }
        return ret;
    }

    public boolean updateVisitCount(BlogInfo blogInfo) {//用户访问
        boolean ret = false;
        ret = this.dao.update(blogInfo);
        return ret;
    }

    public List getTopBlogUser(String types, int elite, String orderBy,
            int topNum) {
        String scope = "1=1 ";
        java.util.Collection<Object> paras = new java.util.ArrayList<Object>();
        if (types != null && (!"".equals(types))) {
            scope += " and type=?";
            paras.add(types);
        }
        if (elite > 0) {
            scope += " and elite>=" + elite;
        }
        scope += " order by " + orderBy;
        DbPageList pList = new DbPageList(BlogInfo.class, scope, paras);
        pList.doList(1, topNum);
        return pList.getResult();
    }

    public void blogInfoChange(BlogInfo blog) {
        blog.setUpdated(Boolean.TRUE);
        this.dao.update(blog);
    }

    public static void main(String[] args) {
        BlogUserServiceImpl service = BlogUserServiceImpl.getInstance();
        service.check("2286227218333570");
    }

    public boolean add(BlogUser user) {
        return this.dao.save(user);
    }

    public boolean updateMailConfig(String blogid, String smtp, String ip, String needauth, String email, String mailpass) {
        boolean ret = false;
        //更新博客和个人信息
        BlogInfo blog = this.getBlogInfo(blogid);
        if (blog == null) {
            return false;
        }
        if (!blog.getEmail().equals(email)) {
            blog.setEmail(email);
            settingBlogInfo(blog);
        }
        BlogUser user = this.getBlogUser("admin");
        if (user == null) {
            return false;
        }
        if (!user.getEmail().equals(email)) {
            user.setEmail(email);
            updateUserInfo(user);
        }
        ret = com.knife.blog.service.Config.saveMailconfig(email, smtp, ip, needauth, mailpass);//更新配置文件
        return ret;
    }

    public boolean sendValidmail(BlogUser user) {
        boolean ret = false;
        String email = user.getEmail();
        SendMail sendmail = new SendMail();
        HashMap hashmap = null;
        String code = Config.getValidationCode();
        ActionContext.getContext().getSession().setAttribute("findPassValid", code);
        ActionContext.getContext().getSession().setAttribute("findPassUser", user.getCid());
        ActionContext.getContext().getSession().setAttribute("findPassStartTime", System.currentTimeMillis());
        try {
            hashmap = sendmail.sendValidateEmail(user.getCid(), email, "", code);
            if (hashmap.get("state").equals("success")) {
                ret = true;
            }
            System.out.println("发送：" + hashmap.get("state"));
        } catch (Exception e) {
            System.out.println("发送：" + hashmap.get("state"));
        }
        return ret;
    }

    public boolean removeBlog(BlogInfo bloginfo) {
        String fileName = bloginfo.getDomain();
        File file = new File(Globals.APP_BASE_DIR + "/" + fileName);
        return com.knife.blog.util.BlogFileUtil.removeDire(file.getAbsolutePath());
    }

    public ActiveUser login(String username, String password, String cktime,
            String ip) {
        ActiveUser user = null;
        BlogUser u = (BlogUser) this.dao.getBy(BlogUser.class, "username",
                username);
        System.out.println("bloguser:" + u.getUsername());
        if (u != null && password.equals(u.getPassword().trim())) {
            user = new ActiveUser();
            user.setUserName(username);
            user.setIp(ip);
            user.setCurPosition("当前位置");
            user.setPassword(u.getPassword().trim());
            user.setLoginTime(new Date());
            u.setUsername(username);
            u.setLastloginip(ip);
            u.setLogintimes(new Integer(u.getLogintimes() == null ? 1 : u.getLogintimes().intValue() + 1));
            this.dao.update(u);
            // activeUserService.join(user);
        }
        String value = username + "_" + password;

        return user;
    }

    public List getTopNewBlogInfo(String orderBy, int currentPage, int pageSize) {
        String scope = "isNew>0 order by " + orderBy;
        java.util.Collection<Object> paras = new java.util.ArrayList<Object>();
        DbPageList pList = new DbPageList(BlogInfo.class, scope, paras);
        pList.doList(currentPage, pageSize);
        return pList.getResult();
    }

    public boolean setBlogInfoNew(String cid, int isNew) {
        try {
            BlogUser bloguser = getBlogUser("cid", cid);
            if (bloguser == null) {
                return true;
            }
            String username = bloguser.getUsername();
            BlogInfo bloginfo = getUserBlog("username", username);
            bloginfo.setIsnew(isNew);
            blogInfoChange(bloginfo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public List getTopEliteBlogInfo(String orderBy, int currentPage,
            int pageSize) {
        String scope = "elite>1 order by " + orderBy;
        java.util.Collection<Object> paras = new java.util.ArrayList<Object>();
        DbPageList pList = new DbPageList(BlogInfo.class, scope, paras);
        pList.doList(currentPage, pageSize);
        return pList.getResult();
    }

    public boolean setBlogInfoElite(String cid, int elite) {
        try {
            BlogUser bloguser = getBlogUser("cid", cid);
            if (bloguser == null) {
                return true;
            }
            String username = bloguser.getUsername();
            BlogInfo bloginfo = getUserBlog("username", username);
            bloginfo.setElite(elite);
            blogInfoChange(bloginfo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public List getTopHotBlogInfo(String orderBy, int currentPage, int pageSize) {
        String scope = "isHot>0 order by " + orderBy;
        java.util.Collection<Object> paras = new java.util.ArrayList<Object>();
        DbPageList pList = new DbPageList(BlogInfo.class, scope, paras);
        pList.doList(currentPage, pageSize);
        return pList.getResult();
    }

    public boolean setBlogInfoHot(String cid, int isHot) {
        try {
            BlogUser bloguser = getBlogUser("cid", cid);
            if (bloguser == null) {
                return true;
            }
            String username = bloguser.getUsername();
            BlogInfo bloginfo = getUserBlog("username", username);
            bloginfo.setIshot(isHot);
            blogInfoChange(bloginfo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
